package com.echo.neocommunity.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.echo.neocommunity.pojo.Message;
import com.echo.neocommunity.pojo.MyPage;
import com.echo.neocommunity.pojo.User;
import com.echo.neocommunity.service.MessageService;
import com.echo.neocommunity.service.impl.MessageServiceImpl;
import com.echo.neocommunity.service.impl.UserServiceImpl;
import com.echo.neocommunity.utils.CommunityConstant;
import com.echo.neocommunity.utils.HostHolder;
import com.echo.neocommunity.utils.R;
import com.echo.neocommunity.utils.SensitiveFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
@RequestMapping("/letter")
public class MessageController {

    @Autowired
    private SensitiveFilter filter;

    @Autowired
    private MessageServiceImpl messageService;
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserServiceImpl userService;

    @GetMapping("/list")
    public String getList(Model model,Long current){
        if(current==null||current==0)
            current=(long)1;
        MyPage page=new MyPage();
        page.setPath("/letter/list");
        page.setCurrent(current);
        User user = hostHolder.getUser();
        int count = messageService.findConversationCount(user.getId());
        page.setTotal((long)count);
        page.setPages((long)(count%5==0?count/5:count/5+1));
        List<Message> list = messageService.findConversation(user.getId(), (Math.toIntExact(page.getCurrent())-1)*5, 5);
        List<Map<String,Object>> conversations=new ArrayList<>();
        if(list!=null){
            for (Message message : list) {
                Map<String,Object> map=new HashMap<>();
                map.put("message",message);
                map.put("letterCount",messageService.selectLetterCount(message.getConversationId()));
                map.put("unreadCount",messageService.selectLetterUnreadCount(user.getId(),message.getConversationId()));
                int targetId= user.getId()==message.getFromId()? message.getToId() : message.getFromId();
                User targetUser = userService.getUserById(targetId);
                map.put("target",targetUser);
                conversations.add(map);
            }
        }
        model.addAttribute("conversations",conversations);
        model.addAttribute("letterUnreadCount",messageService.selectLetterUnreadCount(user.getId(),null));
        model.addAttribute("page",page);
        int noticeUnreadCount= messageService.messageUnreadCount(user.getId(),null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);
        return "/site/letter";
    }

    @GetMapping("/detail/{conversationId}")
    public String getLetterDetail(@PathVariable("conversationId") String conversationId,Long current,Model model){
        if(current==null || current==0)
            current=(long)1;
        MyPage page=new MyPage();
        page.setPath("/letter/detail/"+conversationId);
        page.setCurrent(current);
        int count = messageService.selectLetterCount(conversationId);
        page.setTotal((long)count);
        page.setPages((long)(count%5==0?count/5:count/5+1));
        List<Message> messages = messageService.selectLetters(conversationId, (Math.toIntExact(page.getCurrent()) - 1) * 5, 5);
        List<Map<String,Object>> list=new ArrayList<>();
        if(messages!=null){
            for (Message message : messages) {
                Map<String,Object> map=new HashMap<>();
                if(message.getStatus()==0 && message.getToId()==hostHolder.getUser().getId()){
                    message.setStatus(1);
                    messageService.updateById(message);
                }
                map.put("message",message);
                map.put("fromUser",userService.getUserById(message.getFromId()));
                list.add(map);
            }
        }
        model.addAttribute("letters",list);
        model.addAttribute("page",page);
        model.addAttribute("target",getUser(conversationId));
        return "/site/letter-detail";
    }

    public User getUser(String conversationId){
        if(conversationId==null)
            return null;
        String[] s = conversationId.split("_");
        int userOne=Integer.valueOf(s[0]);
        int userTwo=Integer.valueOf(s[1]);
        User user = hostHolder.getUser();
        return userOne==user.getId()?userService.getUserById(userTwo):userService.getUserById(userOne);
    }

    @PostMapping("/add")
    @ResponseBody
    public R addMessage(String username,String content){
       if(username==null || content==null || username.length()==0 || content.length()==0){
           return R.error(-1,"发送对象或内容为空！");
       }
       Message message=new Message();
       message.setContent(filter.filterText(HtmlUtils.htmlEscape(content)));
       message.setStatus(0);
       message.setCreateTime(new Date());
       QueryWrapper<User> queryWrapper=new QueryWrapper<>();
       queryWrapper.eq("username",username);
       User one = userService.getOne(queryWrapper);
        User user = hostHolder.getUser();
        message.setFromId(user.getId());
        message.setToId(one.getId());
        if(one.getId()<user.getId()){
            message.setConversationId(one.getId()+"_"+ user.getId());
        }else{
            message.setConversationId(user.getId()+"_"+one.getId());
        }
        messageService.save(message);
        return R.ok("发送私信成功！");
    }

    @GetMapping("/notice/list")
    public String getNoticeList(Model model){
        User user = hostHolder.getUser();
        //查询评论类
        Message messageComment = messageService.selectLastNotice(user.getId(), CommunityConstant.TOPIC_COMMENT);
        Map<String,Object> comment=new HashMap<>();
        if(messageComment!=null){
            comment.put("message",messageComment);
//            String content = HtmlUtils.htmlEscape(messageComment.getContent());
            String content=messageComment.getContent();
            System.out.println("content=>>>>"+content);
            HashMap<String,Object> map = JSON.parseObject(content, HashMap.class);
            comment.put("user",userService.getUserById((Integer) map.get("userId")));
            comment.put("entityType",map.get("entityType"));
            comment.put("entityId",map.get("entityId"));
            comment.put("postId",map.get("postId"));
            int commentTotalCount = messageService.messageCount(user.getId(), CommunityConstant.TOPIC_COMMENT);
            int commentUnreadCount = messageService.messageUnreadCount(user.getId(), CommunityConstant.TOPIC_COMMENT);
            comment.put("totalCount",commentTotalCount);
            comment.put("unreadCount",commentUnreadCount);
        }
        model.addAttribute("commentNotice",comment);
        //查询点赞类
        Message messageLike = messageService.selectLastNotice(user.getId(), CommunityConstant.TOPIC_LIKE);
        Map<String,Object> like=new HashMap<>();
        if(messageLike!=null){
            like.put("message",messageLike);
//            String content = HtmlUtils.htmlEscape(messageLike.getContent());
            String content=messageLike.getContent();
            System.out.println("content===>>>"+content);
            HashMap<String,Object> map = JSONObject.parseObject(content, HashMap.class);
            like.put("user",userService.getUserById((Integer) map.get("userId")));
            like.put("entityType",map.get("entityType"));
            like.put("entityId",map.get("entityId"));
            like.put("postId",map.get("postId"));
            int commentTotalCount = messageService.messageCount(user.getId(), CommunityConstant.TOPIC_LIKE);
            int commentUnreadCount = messageService.messageUnreadCount(user.getId(), CommunityConstant.TOPIC_LIKE);
            like.put("totalCount",commentTotalCount);
            like.put("unreadCount",commentUnreadCount);
        }
        model.addAttribute("likeNotice",like);
        //查询关注类
        Message messageFollow = messageService.selectLastNotice(user.getId(), CommunityConstant.TOPIC_FOLLOW);
        Map<String,Object> follow=new HashMap<>();
        if(messageFollow!=null){
            follow.put("message",messageFollow);
//            String content = HtmlUtils.htmlEscape(messageLike.getContent());
            String content=messageFollow.getContent();
            System.out.println("content====>>"+content);
            HashMap<String,Object> map = JSON.parseObject(content, HashMap.class);
            follow.put("user",userService.getUserById((Integer) map.get("userId")));
            follow.put("entityType",map.get("entityType"));
            follow.put("entityId",map.get("entityId"));
            follow.put("postId",map.get("postId"));
            int commentTotalCount = messageService.messageCount(user.getId(), CommunityConstant.TOPIC_FOLLOW);
            int commentUnreadCount = messageService.messageUnreadCount(user.getId(), CommunityConstant.TOPIC_FOLLOW);
            follow.put("totalCount",commentTotalCount);
            follow.put("unreadCount",commentUnreadCount);
        }
        model.addAttribute("followNotice",follow);
        int letterUnreadCount=messageService.selectLetterUnreadCount(user.getId(),null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        int noticeUnreadCount= messageService.messageUnreadCount(user.getId(),null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);
        return "/site/notice";

    }

    @GetMapping("/notice/{type}")
    public String getNoticeDetails(Model model,@PathVariable("type")String type,Long current){
        if(current==null || current==0){
            current=(long)1;
        }
        User user= hostHolder.getUser();
        if(StringUtils.isBlank(type)){
            throw  new RuntimeException("路径为空");
        }
        int total = messageService.messageCount(user.getId(), type);
        MyPage page=new MyPage();
        page.setPath("/letter/notice/"+type);
        page.setTotal((long)total);
        page.setCurrent(current);
        page.setPages((long)(total%6==0?total/6:total/6+1));
        model.addAttribute("page",page);
        List<Map<String,Object>> list=new ArrayList<>();
        List<Message> messages = messageService.selectAllNotice(user.getId(),type, Math.toIntExact((current-1)*6), 6);
        if(messages!=null){
            for (Message message : messages) {
                Map<String,Object> map=new HashMap<>();
                if(message.getStatus()==0){
                    message.setStatus(1);
                }
                messageService.updateById(message);
                map.put("message",message);
                String content = message.getContent();
                HashMap<String,Object> contentMap = JSONObject.parseObject(content, HashMap.class);
                System.out.println("contentMap====>>>>"+contentMap);
                Integer userId = (Integer) contentMap.get("userId");
                User userById = userService.getUserById(userId);
                map.put("user",userById);
                map.put("entityType",contentMap.get("entityType"));
                map.put("entityId",contentMap.get("entityId"));
                System.out.println("topic=======>>>"+contentMap.get("topic"));

                if(!"follow".equals(contentMap.get("topic"))){
                    HashMap<String,Object> data = (HashMap) contentMap.get("data");
                    System.out.println("data=======>>>>content"+data);
                    if(data.size()!=0){
                        map.put("postId", data.get("postId"));
                    }
                }
                list.add(map);
            }
        }
        int typeId=0;
        if(type.equals("comment")){
            typeId=0;
        }else if(type.equals("like")){
            typeId=1;
        }else{
            typeId=2;
        }
        model.addAttribute("type",typeId);
        model.addAttribute("user",user);
        model.addAttribute("noticeList",list);
        return "/site/notice-detail";
    }



}
